package com.zbzly.video.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.io.file.FileWriter;
import com.zbzly.video.properties.RtmpProperties;
import com.zbzly.video.service.M3u8Service;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@RestController
@RequestMapping("/video")
public class VideoController {
    private final String HTTP_PREFIX = "http://127.0.0.1:12321";
    @Autowired
    private RtmpProperties rtmpProperties;
    @Autowired
    private M3u8Service m3u8Service;
    private final String PATH = "/video/hls/";

    @GetMapping("/test")
    public String test() {
        return "test";
    }

    @PostMapping("/record")
    public void uploadToM3u8() throws Exception {
        String m3u8Url = HTTP_PREFIX + "/video/upload/test.m3u8";
        String infoUrl = HTTP_PREFIX + "/key/secret.info";
        m3u8Service.start2m3u8(rtmpProperties.getUrl(), m3u8Url, infoUrl);
    }

    @PostMapping("/upload/{fileName}")
    public void upload(HttpServletRequest request, @PathVariable("fileName") String fileName) throws IOException {
        ServletInputStream inputStream = request.getInputStream();
        FileWriter writer = new FileWriter(PATH + fileName);
        writer.writeFromStream(inputStream);
        IoUtil.close(inputStream);
    }

    /**
     * 预览加密文件
     */
    @RequestMapping("/preview/{fileName}")
    public void preview(@PathVariable("fileName") String fileName, HttpServletResponse response) throws IOException {
        FileReader fileReader = new FileReader(PATH + fileName);
        fileReader.writeToStream(response.getOutputStream());
    }

    /**
     * 预览加密文件
     */
    @GetMapping("/download/{fileName}")
    public void download(@PathVariable("fileName") String fileName, HttpServletResponse response) throws IOException {
        FileReader fileReader = new FileReader(PATH + fileName);
        fileReader.writeToStream(response.getOutputStream());
    }
}
